package com.example.webviewexample;

import android.webkit.WebSettings;
import android.webkit.WebView;

public class Controller implements WebViewController,
        WebViewViewSourceInterface {

    private WebView mWebView;
    private ExampleWebViewClient mWebViewClient;
    private ExampleWebChromeClient mWebChromeClient;
    private JavaScriptLocalObject mJsLocalObject = null;
    private String mJsInterfaceName = "local_obj";
    private String mJsInterfaceGetSourceMethod = "setSource";

    private String mHtml = null;
    private WebViewController mObserver;

    public Controller(WebView webview) {
        mWebView = webview;

        initWebView();
    }

    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setDefaultTextEncodingName("utf-8");

        mWebView.requestFocus();

        mWebViewClient = new ExampleWebViewClient(Controller.this);

        mJsLocalObject = new JavaScriptLocalObject();
        mJsInterfaceName = "local_obj";
        mJsInterfaceGetSourceMethod = "setSource";

        mWebView.addJavascriptInterface(mJsLocalObject, mJsInterfaceName);
        mWebViewClient.setJavaScriptInterface(mJsLocalObject, mJsInterfaceName);
        mWebViewClient.setGetSourceMethod(mJsInterfaceGetSourceMethod);
        mWebView.setWebViewClient(mWebViewClient);

        mWebChromeClient = new ExampleWebChromeClient(Controller.this);
        mWebView.setWebChromeClient(mWebChromeClient);
    }

    public void setObserver(WebViewController observer) {
        mObserver = observer;
    }

    @Override
    public void loadUrl(String url) {
        if (mWebView != null) {
            mWebView.loadUrl(url);
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (mJsLocalObject != null) {
            mHtml = mJsLocalObject.getSource();
        }

        if (mObserver != null) {
            mObserver.onPageFinished(view, url);
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        // TODO Auto-generated method stub

    }

    @Override
    public String getSource() {
        if (mHtml != null) {
            return mHtml;
        }

        if (mJsLocalObject != null) {
            mHtml = mJsLocalObject.getSource();
            return mHtml;
        }
        return null;
    }

    @Override
    public void setJavaScriptInterface(JavaScriptLocalObject obj,
            String interfaceName) {
        mJsLocalObject = obj;
        mJsInterfaceName = interfaceName;

        if (mWebViewClient != null) {
            mWebViewClient.setJavaScriptInterface(obj, interfaceName);
        }
    }
}
